<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="Search" />
      <el-button type="primary" @click="Search">查询</el-button>
      <el-button type="primary" @click="addBuilding">添加楼宇</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="buildingList"
      >
        <el-table-column
          type="index"
          label="序号"
        />
        <el-table-column
          label="楼宇名称"
          width="180"
          prop="name"
        />
        <el-table-column
          label="层数"
          prop="floors"
        />
        <el-table-column
          label="在管面积(m²)"
          width="120"
          prop="area"
        />
        <el-table-column
          label="物业费(元/m²)"
          width="120"
          prop="propertyFeePrice"
        />
        <el-table-column label="状态" prop="status">
          <template #default="obj"> {{ formatStatus(obj.row.status) }}   </template>
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="editBuildList(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              @click="delBuilding(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="page-container">
      <!--分页器-->
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        @current-change="pageChange"
      />
    </div>
    <!-- 添加楼宇弹框 -->
    <el-dialog
      :title="addForm.id ? '编辑楼宇': '添加楼宇' "
      :visible="dialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" style="display: flex; flex-wrap: wrap;justify-content: space-evenly;">
          <el-form-item label="楼宇名称" prop="name" style="width:40%">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors" style="width:40%">
            <el-input v-model="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area" style="width:40%">
            <el-input v-model="addForm.area" />
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice" style="width:40%">
            <el-input v-model="addForm.propertyFeePrice" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmBuilding">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { utils, writeFileXLSX } from 'xlsx'
import { getBuildingListAPI, createBuildingListAPI, delBuildingListAPI, editBuildingAPI } from '@/api/building'
export default {
  name: 'Building',
  data() {
    return {
      buildingList: [],
      params: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      total: 0,
      dialogVisible: false,
      addForm: {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入楼宇层数', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入楼宇面积', trigger: 'blur' }
        ],
        propertyFeePrice: [
          { required: true, message: '请输入楼宇物业费', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getBuildingList()
  },
  methods: {
    // 导出ex表格
    async exportToExcel() {
      const res = await getBuildingListAPI(this.params)
      const tableHeader = ['name', 'floors', 'area', 'propertyFeePrice', 'status']
      // 处理数据保证
      const sheetData = res.data.rows.map((item) => {
        const obj = {}
        tableHeader.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })
      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 把工作表添加到工作簿
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [['楼宇名称', '层数', '在管面积(㎡)', '物业费(㎡)', '状态']], { origin: 'A1' })
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    },
    // 编辑楼宇
    editBuildList(row) {
      this.dialogVisible = true
      const { id, area, floors, name, propertyFeePrice } = row
      this.addForm = { id, area, floors, name, propertyFeePrice }
    },
    // 删除楼宇
    delBuilding(id) {
      this.$confirm('您确定要删除此楼宇吗？', '温馨提示').then(async() => {
        await delBuildingListAPI(id)
        this.getBuildingList()
        this.$message.success('删除成功')
      }).catch(() => {})
    },
    // 确定添加
    confirmBuilding() {
      this.$refs.addForm.validate(async flag => {
        if (!flag) return
        // 判断是添加还是编辑
        if (this.addForm.id) {
          await editBuildingAPI(this.addForm)
          this.$message.success('编辑成功')
        } else {
          await createBuildingListAPI(this.addForm)
          this.$message.success('添加成功')
        }
        this.getBuildingList()
        this.closeDialog()
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false
      this.$refs.addForm.resetFields()
      delete this.addForm.id
    },
    // 添加楼宇
    addBuilding() {
      this.dialogVisible = true
    },
    // 查询
    Search() {
      this.params.page = 1
      this.getBuildingList()
    },
    // 页面变化
    pageChange(page) {
      this.params.page = page
      this.getBuildingList()
    },
    // 渲染页面
    async getBuildingList() {
      const res = await getBuildingListAPI(this.params)
      this.buildingList = res.data.rows
      this.total = res.data.total
      // console.log(res)
    },
    formatStatus(status) {
      const MAP = {
        0: '租赁中',
        1: '闲置中'
      }
      return MAP[status]
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container{
  padding:10px;
}
.search-container{
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237,237,237,.9);;
  padding-bottom: 20px;
  .search-label{
    width:100px;
  }
  .search-main{
    width: 220px;
    margin-right: 10px;
  }
}
.page-container{
    padding:4px 0px;
    text-align: right;
  }

</style>
